import requests
import time
import random
from loguru import logger
from work.get_100_keys import get_100_keys_id
from work.search_site_list import get_site_id


def recheck_keys(company_info, user):
    headers = {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        "baggage": "sentry-environment=production,sentry-public_key=9b4a6569c04148aa9ab275932e8b1961,sentry-trace_id=6d3c87b36e644447aa41b966f7c05994",
        "cache-control": "no-cache",
        "content-type": "application/x-www-form-urlencoded",
        "origin": "https://online.seranking.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://online.seranking.com/admin.site.rankings.site_id-7535981.html?ref=left_menu_clicked",
        "sec-ch-ua": "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "sentry-trace": "6d3c87b36e644447aa41b966f7c05994-883ed211bb97959d",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "x-requested-with": "XMLHttpRequest"
    }
    cookies = user['cookies']
    matching_project = get_site_id(company_info=company_info, user=user)
    if matching_project == 0:
        return f"账号: {user['account']} -----> 没有 {company_info['company_name']} 该项目"
    keyword_ids = get_100_keys_id(matching_project=matching_project, cookies=cookies)
    if matching_project == 0:
        return f"账号: {user['account']} -----> 没有 {company_info['company_name']} 该项目"

    url = "https://online.seranking.com/api.projects.site.positions.recheck.html"
    data = {
        "do": "getAmount",
        "site_id": str(matching_project['site_id']),
        "type": "selected",
        f"selected[{str(matching_project['site_se_id'])}][keywords]": keyword_ids
    }
    retry_count = 0
    while retry_count < 3:
        try:
            res = requests.post(url, data=data, cookies=cookies, headers=headers, timeout=5)
        except Exception as e:
            logger.error(f"{user['account']}: {company_info['company_name']} ----> 请求超时: {e}")
            time.sleep(random.randint(1, 2))
            retry_count += 1
            continue
        if res.status_code == 200:
            data = res.json()
            total_check_count = data["data"][str(matching_project['site_id'])]["total_check_count"]
            logger.info(f"{matching_project['company_name']} -----> 共有{total_check_count}个关键词需要复查")
            break
        else:
            logger.error(f"复查异常 ----> {res.status_code}")
            return 0

    time.sleep(random.randint(1, 2))

    headers = {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        "baggage": "sentry-environment=production,sentry-public_key=9b4a6569c04148aa9ab275932e8b1961,sentry-trace_id=0358230aed8a44d0998348189ea070f5",
        "cache-control": "no-cache",
        "content-type": "application/x-www-form-urlencoded",
        "origin": "https://online.seranking.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://online.seranking.com/admin.site.rankings.site_id-8286431.html?ref=project_select_clicked",
        "sec-ch-ua": "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "sentry-trace": "0358230aed8a44d0998348189ea070f5-b87c304e3c06b210",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "x-requested-with": "XMLHttpRequest"
    }

    url = "https://online.seranking.com/api.projects.site.positions.recheck.html"
    params = {
        "do": "recheck"
    }
    data = {
        "do": "recheck",
        "site_id": str(matching_project['site_id']),
        "type": "selected",
        f"selected[{str(matching_project['site_se_id'])}][keywords]": keyword_ids
    }
    retry_count = 0
    while retry_count < 3:
        try:
            res = requests.post(url, params=params, data=data, headers=headers, cookies=cookies, timeout=5)
        except Exception as e:
            logger.error(f"{user['account']}: {company_info['company_name']} ----> 请求超时: {e}")
            time.sleep(random.randint(1, 2))
            retry_count += 1
            continue
        if res.status_code == 200:
            data = res.json()
            if data['data'].get("message"):
                logger.success(f"{matching_project['company_name']} ------> 复查成功，请稍后等待刷新")
                return 1
            else:
                logger.error(f"{matching_project['company_name']} ------> 复查失败，{data}")
                return 0
        else:
            logger.error(f"{matching_project['company_name']} ----> 复查进行中失败")
            return 0